#include "LoadBackground.h"


CLoadBackground::CLoadBackground()
{
	TotalLine = 0;
	TotalTile = 0;
	_widthMap = _heightMap = 0;
}
void CLoadBackground::ImportFile(char *FileName)
{
	int i = 0;
	ifstream File(FileName);
	//File.open(FileName,ios::in);
	if(File.is_open())
	{
		string total;			//Lay dong dau tien -> xac dinh tong so doi tuong
		//getline(File,total);
		//TotalLine = StringToInt(total);
		File >> _widthMap >> _heightMap;
		//getline(File,total);
		File>> TotalTile;
		//TotalTile = StringToInt(total);
		/*for(int i = 0;i<TotalLine;i++)
		{*/
		while(!File.eof())
		{
			string Line;
			getline(File,Line);
			SplitString(Line,i);
			i++;
		}
	}
	File.close();
}

//Method: "ReadString"
//Cat chuoi thanh 3 phan tuong ung voi ID, X, Y
void CLoadBackground::SplitString(string line, int i)
{
	string id;		//Id cua doi tuong;
	string posX, posY;	//Vi tri cua doi tuong trong map
	string Delimiter = " ";	//Xac dinh vi tri can cat
	size_t Pos = 0;
	while((Pos = line.find(Delimiter)) != string::npos)
	{
		if(id == "")
			id = line.substr(0,Pos);
		else posX = line.substr(0,Pos);
		line.erase(0, Pos + Delimiter.length());
	}
	posY = line;
	Object.push_back(CObject(StringToInt(id), StringToInt(posX), StringToInt(posY)));
}

void CLoadBackground::SplitString(string line)
{
	string _width, _height;		//Id cua doi tuong;
	string Delimiter = " ";	//Xac dinh vi tri can cat
	size_t Pos = 0;
	while((Pos = line.find(Delimiter)) != string::npos)
	{
		if(_width == "")
			_width = line.substr(0,Pos);
		else _height = line.substr(0,Pos);
		line.erase(0, Pos + Delimiter.length());
	}
	_widthMap = StringToInt(_width);
	_heightMap = StringToInt(_height);
}

int CLoadBackground::StringToInt(string text)
{
	int Result;
	Result = atoi(text.c_str());
	return Result;
}

void CLoadBackground::AddResource()
{
	Background = new CSprite(new CTexture("image/1.png", TotalTile, 1, TotalTile));
}
void CLoadBackground::DrawMap(CCamera *Camera)
{
	list<CObject>::iterator _itBegin, _itEnd; // 2 con tro dung de duyet 
	_itBegin = Object.begin(); // con tro dau mang 
	_itEnd = Object.end(); // con tro cuoi mang 

	for(_itBegin; _itBegin != _itEnd; _itBegin++)
	{
		D3DXVECTOR2 t = Camera->Transform(_itBegin -> GetX(), _itBegin -> GetY());
		Background->DrawIndex(_itBegin -> GetID(), t.x, t.y);
	}
}